import Router from 'koa-router';
import { Logger, resFail, resSuccess } from '../utils';
import { findInsure, findInsureById, insertInsure, removeInsureById } from '../db';

const router: Router = new Router();

router.post('/add', async (ctx) => {
  const { body }: any = ctx.request;
  try {
    const doc = await insertInsure(body);
    ctx.response.body = resSuccess(doc);
  } catch (error) {
    Logger.error(error);
    ctx.response.body = resFail('插入失败');
  }
});

router.get('/delete', async (ctx) => {
  const { query }: any = ctx.request;
  try {
    const doc = await removeInsureById(query.id);
    ctx.response.body = resSuccess('删除成功！');
  } catch (error) {
    Logger.error(error);
    ctx.response.body = resFail('删除失败');
  }
});

router.get('/list', async (ctx: any) => {
  try {
    const insureList = await findInsure();
    ctx.response.body = resSuccess(insureList);
  } catch (error) {
    Logger.error(error);
    ctx.response.body = resFail('查询失败');
  }
});

router.post('/detail', async (ctx: any) => {
  const { body } = ctx.request;
  const { id } = body || {};
  if (!id) {
    ctx.response.body = resFail('id错误');
    return;
  }

  try {
    const doc = await findInsureById(id);
    ctx.response.body = resSuccess(doc);
  } catch (error) {
    Logger.error(error);
    ctx.response.body = resFail('查询失败');
  }
});

export default router.routes();
